package com.geek.pokermanager.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.IntStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.geek.pokermanager.base.BaseController;
import com.geek.pokermanager.model.PokerFaceFile;
import com.geek.pokermanager.model.PokerGroup;
import com.geek.pokermanager.model.RequestModel;
import com.geek.pokermanager.model.User;
import com.geek.pokermanager.service.PokerGrupService;
import com.geek.pokermanager.util.ConfigTool;
import com.geek.pokermanager.util.FileTools;
import com.geek.pokermanager.util.HttpUtils;
import com.geek.pokermanager.util.JacksonUtil;
import com.geek.pokermanager.util.UUIDTool;

/**
 * 扑克管理控制器
 * @author Administrator
 *
 */
@Controller
@RequestMapping(value="pokermgr")
public class PokerManagerController extends BaseController{
	
	@Autowired
	private PokerGrupService pokerGroupService;
	
	private Map<String,List<PokerGroup>> data=new HashMap<String,List<PokerGroup>>();
	
	private Map<String,Map<String,Integer>> user=new HashMap<String,Map<String,Integer>>();
	
	@ResponseBody
	@RequestMapping(value="getImageOrderPath",method=RequestMethod.POST, produces = "text/html;charset=utf8")
	public String getImageOrderPath(HttpServletRequest request,HttpServletResponse response) throws IOException{
		String pokerFolderPath=request.getSession().getServletContext().getRealPath("image/pokerFace");
		returnResult.setData(FileTools.getFile(pokerFolderPath));
		return resultVal();
	}
	
	
	@RequestMapping(value="mainPage")
	public String mainView(Model model) throws IOException{
		model.addAttribute("Context",basePath());
		model.addAttribute("ContextPath",request.getContextPath());
    	String pokerFolderPath=request.getSession().getServletContext().getRealPath("image/pokerFace");
    	model.addAllAttributes(FileTools.getFile(pokerFolderPath));
		return "controller";
	}
	@ResponseBody
	@RequestMapping(value="getPlayInfo",method=RequestMethod.POST, produces = "text/html;charset=utf8")
	public String getPlayInfo(String playerId) {
		List<String> args = new ArrayList<String>();
		RequestModel requestModel = new RequestModel();
		requestModel.setCmd("selectPlayer");
		args.add(playerId);
		requestModel.setArgs(args);
		String json = JacksonUtil.getJsonFromObject(requestModel);
		String result="{\"error\":\"true\"}";
		try {
			result = HttpUtils.PostWithJson(json);
		} catch (Exception e) {
			returnResult.setError(true);
			returnResult.setMsg("链接游戏服务器失败！"+e.getMessage());
			System.err.println(e.getMessage());
			return resultVal();
		}
		return result;
	}
	
	@ResponseBody
	@RequestMapping(value="getAlreadyInfo",method=RequestMethod.POST, produces = "text/html;charset=utf8")
	public String getAlreadyInfo(String roomId) {
		List<PokerGroup> group=this.data.get(roomId);
		if(group==null || group.size()<1){
			returnResult.setError(true);
			returnResult.setMsg(roomId+"房间数据已全部发送完毕！");
			return resultVal();
		}
		for (PokerGroup pokerGroup : group) {
			PokerGroup temp=pokerGroupService.getGroupData(pokerGroup.getPokerGroupId());
			pokerGroup.setPokerGroupName(temp.getPokerGroupName());
			pokerGroup.setPokerData(temp.getPokerData());
			pokerGroup.setPokerGroupNo(temp.getPokerGroupNo());
			pokerGroup.setPokerGroupDesc(temp.getPokerGroupDesc());
			
		}
		returnResult.setData(group);
		return resultVal();
	}
	@ResponseBody
	@RequestMapping(value="saveGroup",method=RequestMethod.POST, produces = "text/html;charset=utf8")
	public String savePokerGroup(String groupNo,String groupId,String roomId,String storeId, @RequestBody Map<String,List<PokerFaceFile>> data,HttpServletRequest request) throws UnsupportedEncodingException{
		
		PokerGroup p=new PokerGroup();
		String groupDesc=new String(request.getParameter("groupDesc").getBytes("iso-8859-1"),"utf-8");
		p.setPokerGroupName("牌组"+groupNo);
		p.setPokerGroupNo(groupNo);
		if(StringUtils.isBlank(storeId)){
			storeId="123";
		}
		p.setPokerStoreId(storeId);
		p.setPokerGroupDesc(groupDesc);
		p.setPokerData(data);
		if(StringUtils.isNotBlank(groupId)){
			//修改
			p.setPokerGroupId(groupId);
			pokerGroupService.update(p);
		}else{//新增
			p.setPokerGroupId(UUIDTool.getUUID());
			if(pokerGroupService.save(p)>0){
				returnResult.setMsg("保存成功！");
				if(StringUtils.isNotBlank(roomId)){
					List<PokerGroup> group=this.data.get(roomId);
					if(group!=null){
						group.add(p);
					}
					this.data.put(roomId, group);
				}
			}else{
				returnResult.setError(true);
				returnResult.setMsg("保存失败！");
			}
		}
		return resultVal();
	}
	/**
	 * 根据牌库获取牌组
	 * @param storeId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping(value="getGroup",method=RequestMethod.POST, produces = "text/html;charset=utf8")
	public String getPokerGroup(String storeId){
		if(storeId==null){
			storeId="123";
		}
		returnResult.setData(pokerGroupService.getGroup(storeId));
		return resultVal();
	}
	/**
	 * 删除牌组
	 * @param pokerGroupId
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="delGroup",method=RequestMethod.POST, produces = "text/html;charset=utf8")
	public String delGroup(String pokerGroupId,HttpServletRequest request){
		if(StringUtils.isNotBlank(pokerGroupId)){
			pokerGroupService.delete(pokerGroupId);
			returnResult.setMsg("删除成功！");
		}else{
			returnResult.setError(true);
			returnResult.setMsg("牌组id为空");
		}
		return resultVal();
	}
	@ResponseBody
	@RequestMapping(value="commitData",method=RequestMethod.POST, produces = "text/html;charset=utf8")
	public String commitData(@RequestBody Map map){
		Map user=(Map) map.get("user");
		String roomId=(String) map.get("roomId");
		this.user.put(roomId, user);
		return resultVal();
	}
	
	@ResponseBody
	@RequestMapping(value="commitPoker",method=RequestMethod.POST, produces = "text/html;charset=utf8")
	public String commitPoker(@RequestBody List<PokerGroup> group,String roomId,HttpServletRequest request){
		this.data.put(roomId, group);
		returnResult.setMsg("提交成功！");
		try {
			getRoomData(roomId, request);//提交时发送一次数据
		} catch (Exception e) {
			returnResult.setError(true);
			returnResult.setMsg("提交成功！向游戏服务器发送数据异常！"+e.getMessage());
		}
		return resultVal();
	}
	/**
	 * 向服务器发牌
	 * @param roomId
	 * @param request
	 * @return
	 * @throws IOException
	 * @throws InterruptedException 
	 */
	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping(value="getRoomData",method=RequestMethod.POST, produces = "text/html;charset=utf8")
	public String getRoomData(String roomId,HttpServletRequest request) throws IOException{
		if(StringUtils.isBlank(roomId)){
			roomId = HttpUtils.changeInputStream(request.getInputStream(),"UTF-8");
			if(StringUtils.isBlank(roomId)){
				returnResult.setMsg("无房间号");
				returnResult.setError(true);
				return resultVal();
			}
		}
		System.err.println("已发送:"+roomId);
		List<String> args=new ArrayList<String>();
        RequestModel requestModel=new RequestModel();
        requestModel.setCmd("startPlug");
        List<PokerGroup> group=data.get(roomId);
        if(user==null || group==null || group.size()<1){
        	System.err.println("房间："+roomId+"无作弊数据");
        	return resultVal();
        }
        System.err.println("房间"+roomId+"还有："+group.size());
        PokerGroup p=group.get(0);
        Map<String,Integer> user=(Map<String,Integer>) this.user.get(roomId);
        args.add(roomId);
        for (String userId : user.keySet()) {
        	args.add(userId);
        	p=pokerGroupService.getGroupData(p.getPokerGroupId());
        	List<PokerFaceFile> f=(List<PokerFaceFile>) p.getPokerData().get("poker"+user.get(userId));
        	Integer[] cards=new Integer[f.size()];
        	for (int i=0;i<f.size();i++) {
        		cards[i]=f.get(i).getIndexVal();
			}
        	args.add(JacksonUtil.getJsonFromObject(cards));
		}
        group.remove(0);
        System.err.println("房间"+roomId+"剩余："+group.size());
        this.data.put(roomId, group);
        requestModel.setArgs(args);
        String json = JacksonUtil.getJsonFromObject(requestModel);
        String result = HttpUtils.PostWithJson(json);
        System.err.println(result);
        return resultVal();
	}
	@ResponseBody
	@RequestMapping(value="closeRoonSend",method=RequestMethod.POST, produces = "text/html;charset=utf8")
	public String closeRoomSend(String roomId){
		data.remove(roomId);
		user.remove(roomId);
		returnResult.setMsg("关闭"+roomId+"数据成功");
		returnResult.setData(data.keySet());
		return resultVal();
	}
	@ResponseBody
	@RequestMapping(value="closeAllRoomData",method=RequestMethod.POST, produces = "text/html;charset=utf8")
	public String closeAllRoomData(){
		data=new HashMap<String, List<PokerGroup>>();
		user=new HashMap<String, Map<String,Integer>>();
		returnResult.setMsg("关闭所有房间数据成功");
		return resultVal();
	}
}
